function refreshProductPrecursor(){
	$('#pp_msg').html("<img src='images/demo_wait.gif' />");
	pppage = 0;
	load_ppc(function(){
		ppTAAssociation();
	});
}

function ppTAAssociation(){
	var start = pppage*mconfig['product_precursor_page_limit'];
        var max = pppage*mconfig['product_precursor_page_limit'] + mconfig['product_precursor_page_limit'];
        if (orphan_products.length < max){
        	max = orphan_products.length
        }
        for (var i = start; i < max; i++){
        	if (orphan_products[i] != null){
                	var orphan_cid = orphan_products[i]["id"];
                        $('#' + orphan_cid + '_precid').typeahead({source: precursorTypeAhead.data('typeahead').source,
                        updater: function(sobj) {
                        	var selected_precursor = sobj;
                                var selected_product = this.$element[0].id.split("_")[0];
                                associate_ppc(selected_product, selected_precursor);
                        },items:20});
                }else{
                	console.log("orphan_product is null for i " + i);
                }
        }
}

function nextProductPrecursor(){
	var maxpage = Math.floor(orphan_products.length/mconfig['product_precursor_page_limit']);
	if (pppage == maxpage){
		return;
	}
        $('#pp_msg').html("<img src='images/demo_wait.gif' />");
        pppage = pppage + 1;
	load_ppc(function(){
		ppTAAssociation();
		console.log("loaded next");
        });
}

function previousProductPrecursor(){
	if (pppage == 0){
		return;
	}
        $('#pp_msg').html("<img src='images/demo_wait.gif' />");
        pppage = pppage - 1;
        load_ppc(function(){
                ppTAAssociation();
		console.log("loaded previous");		
        });
}

function load_ppc(callback){
	//check Derivatization Agent value
	var ppc_lookup = $("#ppc_lookup").val();
	if (ppc_lookup == ""){
	    $("#ppc_lookup").val("TMS");
	}
	$.ajax({
        	type: "POST",
                url:  "/cgi-bin/metabobase/get_compound_derivatization.cgi",
                data: {'search_input': ppc_lookup},
                success: function(json){
			if ($.parseJSON(json) == null){new Messi('Error on get_compound_derivatization.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
			var jo  = $.parseJSON(json);
			orphan_products = jo.orphan_products;
			$("#product_precursor_tbl_div").html("");
			var start = pppage*mconfig['product_precursor_page_limit'];
			var previouslink = '<a href="#" onclick="previousProductPrecursor();">&nbsp;<font color="blue">Previous</font></a>';
			if (pppage == 0){
				previouslink = "";
			}
			var max = pppage*mconfig['product_precursor_page_limit'] + mconfig['product_precursor_page_limit']; 
			var nextlink = '<a href="#" onclick="nextProductPrecursor();"><font color="blue">Next</font></a>';
			if (Math.floor(orphan_products.length/mconfig['product_precursor_page_limit']) == pppage){
				nextlink = "";
			}
			var tablestr = _ppc_table_header();
			if (orphan_products.length < max){
			    max = orphan_products.length
			}
			for (var i = start; i < max; i++){
				tablestr = tablestr + _ppc_row(orphan_products[i]);
			}
			var tablestr = tablestr + _ppc_table_end();
			$('#pp_msg').html('<font color="red">Updating ' + (start + 1) + '-' + (i) +  '/' + orphan_products.length + '</font>&nbsp;' + previouslink + '&nbsp;<a href="#" onclick="refreshProductPrecursor();"><font color="blue">Refresh</font></a></font>&nbsp;' + nextlink);
			$("#product_precursor_tbl_div").html(tablestr);
			$('#pp_msg1').html('<font color="red">Updating ' + (start + 1) + '-' + (i) +  '/' + orphan_products.length + '</font>&nbsp;' + previouslink + '&nbsp;<a href="#" onclick="refreshProductPrecursor();"><font color="blue">Refresh</font></a></font>&nbsp;' + nextlink);
			callback();
                },
                error:function(xhr,err){
                	alert("Failed initializing Compound Product-Precursor View DB problem\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                }
        });
}

function _ppc_table_header(){
	return "<form><table  border='0' cellpadding='0'><tr><th width='25%'>Product</th><th width='7%'>Copies</th><th width='25%'>Precursor</th><th width='28%'>Product Formula</th><th width='15%'>Status(*multiple)</th></tr>";
}

function _ppc_table_end(){
	return "</table></form>";
	//add showing x/1000 refresh/link here?
}

/*
	add onchange_ppc for formula field
*/
function onchange_ppc(cpid){
	if (arguments != null && arguments.length >= 1){
		var selected_precursor = $('#' + cpid + '_precid').val();
		var precursorid = "";
		if (selected_precursor != ""){
			for (var jkey in compound_dictionary){
		                var precursor_name = compound_dictionary[jkey];
                		if (precursor_name == selected_precursor){
                        		precursorid = jkey;
					break;
				}
			}
			$.ajax({
                                type: "POST",
                                url:  "/cgi-bin/metabobase/get_librarycompounds.cgi",
                                data: {
                                        'search_input': precursorid,
                                },
                                success: function(json)
                                {
					if ($.parseJSON(json) == null){new Messi('Error on precursor change get_library_compounds.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                                        var jo  = $.parseJSON(json);
                                        var precform = jo.aaData[0][4];
					var xrecopies = $('#' + cpid + '_copyid').val();
                                        var xres = "";
                                        var append_chem = resolve_reagent_chem();
                                        for (var xre = 0; xre < parseInt(xrecopies); xre++){
                                        	xres = xres + append_chem;
                                        }
                                        if (precform != null && precform != "" && precform != "None"){
						var formula = precform + xres;
						$('#' + cpid + '_formid').val(formula);
						var reagentid = resolve_reagent_id();
						post_ppc(cpid, precursorid,reagentid,formula, function(){
							if ($('#' + cpid + '_status').html() != ""){
								$('#' + cpid + '_status').html("<font color='red'>&nbsp;saved2db* <a href='#' onclick='undo_ppc(\"" + cpid + "\");'><i>undo</i></a></font>");
							}else{
								$('#' + cpid + '_status').html("<font color='blue'>&nbsp;saved2db <a href='#' onclick='undo_ppc(\"" + cpid + "\");'><i>undo</i></a></font>");	
							}
							$('#' + cpid + '_precid').val(compound_dictionary[precursorid]);
						});
					}
				}
			});//end ajax
		}
	}
}

function prompt_precursor_formula(cpid, precursor_id, callback) {
    var fla="";
    fla = prompt("Precursor formula is empty, let's fix that:");
    if (fla != null){
	$.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/update_compound_precursors.cgi",
                data: {
                        'compound_id': precursor_id,'product_formula':fla
                },
                success: function(json){
			if ($.parseJSON(json) == null){new Messi('Error on ppc update_compound_precursors.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                        var pa  = $.parseJSON(json);
                        if (pa == null){
				new Messi("Error: Error updating new precursor compound formula", {title: 'Error'});
                                alert("DB Error updating precursor compound formula");
                        }else{
                                if (pa['_status'] == "200"){
                			$('#' + cpid + '_formid').val(fla);  
		                	callback();					
                                }
                        }
                },
                error:function(xhr,err){
                        alert("Failed saving new precursor \nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                }
        });
   }else{
   	callback();
   }
}

function undo_ppc(cpid){
	var opc = {};
	var precursor_id = "";
	var selected_precursor = $('#' + cpid + '_precid').val();
        for (var jkey in compound_dictionary){
                var precursor_name = compound_dictionary[jkey];
                if (precursor_name == selected_precursor){
                        precursor_id = jkey;
			break;
		}
	}
	for (var i = 0; i < orphan_products.length; i++){	
		opc = orphan_products[i];
		if (cpid == opc["id"]){
			break;
		}
	}
	var formula = opc["form"];
	if (formula == null || formula == ""){
		formula = "fnone";
	}
	var reagent = resolve_reagent_id();
	$.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/archive_metabobase.cgi",
                data: { 'compound_id': cpid, 'reagent':reagent, 'precursor_compound':precursor_id, 'datatype':'compound_precursor', 'original_formula':formula},
                success: function(json)
                {
			if ($.parseJSON(json) == null){new Messi('Error on arhive_metabobase.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
			var pa = $.parseJSON(json);
			if (pa == null){
				new Messi("Oh no - Error: Precursor association/formula for " + compound_dictionary[cpid] + ' is reset.', {title: 'Error Undo'});
			}else{
				if (formula == "fnone"){
					formula = "";
				}
				$('#' + cpid + '_formid').val(formula);
				$('#' + cpid + '_precid').val("");
				$('#' + cpid + '_status').html("<font color='purple'>&nbsp;undone</font>");
				new Messi("Precursor association/formula for " + compound_dictionary[cpid] + ' is reset.', {title: 'Undo',autoclose: 1500});
			}
                },
                error:function(xhr,err)
                {
                        alert("Failed undo precursor compound\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                }
        });
}

function post_ppc(cid, pid, reagentid, formula, callback){
	$.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/update_compound_precursors.cgi",
                data: {
                        'compound_id': cid,'precursor_compound_id': pid,'derivatization_reagent_id': reagentid,'product_formula':formula
                },
                success: function(json){
			if ($.parseJSON(json) == null){new Messi('Error on update_compound_precursors.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                        var pa  = $.parseJSON(json);
             		if (pa == null){
				alert("DB Error updating compound precursors");
			}else{
		        	if (pa['_status'] == "200"){
					callback();
				}
			}
                },
                error:function(xhr,err){
                        alert("Failed saving new precursor \nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                }
        });
}

function resolve_reagent_chem(){
	var reagent_chem = $('#ppc_reagent').val();
        var append_chem = "";
        for (var rg in reagent_group_dictionary){
        	if (reagent_chem == rg){
                	append_chem = reagent_group_dictionary[rg];
                        break;
                }
        }
	return append_chem;
}

function resolve_reagent_id(){
	var reagent_chem = $('#ppc_reagent').val();
	var reagentid = "";
        for (var rid in reagent_dictionary){
        	if (reagent_chem == reagent_dictionary[rid]){
                	reagentid = rid;
			break;
                }
        }
	return reagentid;
}
function associate_ppc(cpid, selected_precursor){
	var precform = "";
	var precursorid = "";
	for (var jkey in compound_dictionary){
		var precursor_name = compound_dictionary[jkey];
		if (precursor_name == selected_precursor){
			precursorid = jkey;
			break;
		}
	}
	//$('#' + cpid + '_precid').val(precursor_name);
	$.ajax({
        type: "POST",
        url:  "/cgi-bin/metabobase/get_librarycompounds.cgi",
        data: {'search_input': precursorid},
        success: function(json)
                 {
			if ($.parseJSON(json) == null){new Messi('Error on associate ppc get_library_compounds.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
			var jo  = $.parseJSON(json);
                        precform = jo.aaData[0][4];
			var forumula = "";
			var reagent_chem = resolve_reagent_chem();
                        var reagentid = resolve_reagent_id();
                        var xrecopies = $('#' + cpid + '_copyid').val();
                        var xres = "";
                        for (var xre = 0; xre < parseInt(xrecopies); xre++){
                        	xres = xres + reagent_chem;
                        }
			if (precform != null && precform != "" && precform != "None"){
				var prodform = $('#' + cpid + '_formid').val();
				formula = precform + xres;
				if (prodform != ""){
					new Messi('Update product existing formula ' + prodform + ' with ' + precform + xres + "? (Cancel will not save P-P relationship to DB!)", {title: 'Metabo?', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}, {id: 2, label: 'Cancel', val: 'C'}], 
					callback: function(val) { 
						if (val == 'C'){return;}
						formula = prodform;
						if (val == 'Y'){formula = precform + xres;}
						post_ppc(cpid, precursorid, reagentid, formula, function(){
							$('#' + cpid + '_formid').val(formula);
							if ($('#' + cpid + '_status').html() != "" && $('#' + cpid + '_status').html().indexOf("undone") == -1){
                                                        	$('#' + cpid + '_status').html("<font color='red'>&nbsp;saved2db* <a href='#' onclick='undo_ppc(\"" + cpid + "\");'>undo</a></font>");
                                                        }else{
                                                                $('#' + cpid + '_status').html("<font color='blue'>&nbsp;saved2db <a href='#' onclick='undo_ppc(\"" + cpid + "\");'>undo</a></font>");
                                                        }
							$('#' + cpid + '_precid').val(compound_dictionary[precursorid]);	
						});
					}});

				}else{
					$('#' + cpid + '_formid').val(formula);
					post_ppc(cpid, precursorid,reagentid,formula, function(){
                                        	if ($('#' + cpid + '_status').html() != ""){
                                                	$('#' + cpid + '_status').html("<font color='red'>&nbsp;saved2db* <a href='#' onclick='undo_ppc(\"" + cpid + "\");'>undo</a></font>");
                                                }else{
                                                        $('#' + cpid + '_status').html("<font color='blue'>&nbsp;saved2db <a href='#' onclick='undo_ppc(\"" + cpid + "\");'>undo</a></font>");
                                                }
						$('#' + cpid + '_precid').val(compound_dictionary[precursorid]);
                                        });		
				}
			}else{
				prompt_precursor_formula(cpid, precursorid, function(){
                                	precform = $('#' + cpid + '_formid').val();
                                        formula = ""
					if (precform != ""){
                                        	formula = precform + xres;
						$('#' + cpid + '_formid').val(formula);
					}else{
                                                formula =  $('#' + cpid + '_formid').val();
					}
                                        var reagentid = resolve_reagent_id();
                                        post_ppc(cpid, precursorid,reagentid,formula, function(){
                                        	if ($('#' + cpid + '_status').html() != ""){
                                                	$('#' + cpid + '_status').html("<font color='red'>&nbsp;saved2db* <a href='#' onclick='undo_ppc(\"" + cpid + "\");'>undo</a></font>");
                                                }else{
                                                        $('#' + cpid + '_status').html("<font color='blue'>&nbsp;saved2db <a href='#' onclick='undo_ppc(\"" + cpid + "\");'>undo</a></font>");
                                                }
						$('#' + cpid + '_precid').val(compound_dictionary[precursorid]);
                                        });
                                 });
			}
                },//end success
                error:function(xhr,err){
                	alert("Lookup on " + compound_dictionary[jkey] + " DB Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                }
	});//end ajax
	//break;        		
	//}	
}
function _ppc_row(cpobj){
	if (cpobj == null){
	    return "";
	}
	var cpid = cpobj["id"];
	var product = cpobj["prod"];
	var formula = cpobj["form"];
	if (formula == null || formula == "null"){
		formula = "";
	}
	//var product_cell = "<td>"+product + " " + cpid + "</td>";
	var product_cell = "<td>"+product+"</td>";
	var precursor_cell = "<td><input style='height:30px;width:300px;' type='text' " + "name='" + cpid + "_precid' size='30' id='" + cpid + "_precid' data-provide='typeahead'></td>";
	var copy = 0;
	var lookup = $('#ppc_lookup').val();
	var lind = product.indexOf(lookup);
	if (lind != -1){
		lind = product.substring(lind-1,lind);
		if (lind == ""){
			copy = 0;
		}else if (isNumeric(lind)){
			copy = lind;
		}
	}
	var precursor_copy_cell = "<td><input style='height:30px;width:30px;' type='number' " + "name='" + cpid + "_copyid' size='3' id='" + cpid + "_copyid' value='" + copy + "' onchange=onchange_ppc(\'" + cpid + "\')></td>";
	var product_formula_cell = "<td><input style='height:30px;width:350px;' type='text' " + "name='" + cpid + "_precid' size='50' id='" + cpid + "_formid' value='" + formula + "' onchange=onchange_ppc(\'" + cpid + "\')></td>";
	var ppc_status = "<td><span id='" + cpid + "_status'></span></td>";
	return "<tr>" + product_cell + precursor_copy_cell + precursor_cell + product_formula_cell + ppc_status + "</tr>";
}
